package com.stox.client.ui.javafx.watchlist.model;

import java.util.Collections;
import java.util.List;

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

import com.stox.client.api.core.Client;
import com.stox.shared.watchlist.model.Watchlist;
import com.stox.shared.watchlist.model.WatchlistEntry;

/**
 * An Observable Watchlist
 * 
 * @author paralikar_p
 */
public class OWatchlist extends Watchlist {

	public static final ObservableList<OWatchlist> ALL = FXCollections.observableArrayList();
	private static boolean fetched = false;
	public static synchronized void fetchAll(){
		if(!fetched){
			fetched = true;
			List<Watchlist> watchlists = Client.WATCHLIST.findAll();
			for(Watchlist watchlist : watchlists){
				ALL.add(new OWatchlist(watchlist));
			}
			Collections.sort(ALL);
		}
	}
	public static OWatchlist getWatchlistById(Long watchlistId){
		fetchAll();
		for(OWatchlist watchlist : OWatchlist.ALL){
			if(null != watchlistId && watchlistId.equals(watchlist.getId())){
				return watchlist;
			}
		}
		return null;
	}
	

	private final ObservableList<WatchlistEntry> entries = FXCollections
			.observableArrayList();
	private final StringProperty nameProperty = new SimpleStringProperty();

	public OWatchlist(Watchlist watchlist) {
		setId(watchlist.getId());
		super.setName(watchlist.getName());
		super.setEntries(entries);
		nameProperty.set(watchlist.getName());
		nameProperty.addListener(new ChangeListener<String>(){
			@Override
			public void changed(ObservableValue<? extends String> observable,
					String oldValue, String newValue) {
				OWatchlist.super.setName(newValue);
			}
		});
	}

	public StringProperty nameProperty() {
		return nameProperty;
	}

	@Override
	public void setName(String name) {
		nameProperty.set(name);
	}

	@Override
	public void setEntries(List<WatchlistEntry> entries) {
		throw new UnsupportedOperationException();
	}

	@Override
	public ObservableList<WatchlistEntry> getEntries() {
		return entries;
	}
}
